package com.qiu.demo.util;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class CaptchaUtils {

    // 验证码图片宽度
    private static final int WIDTH = 100;
    // 验证码图片高度
    private static final int HEIGHT = 40;
    // 验证码字符数量
    private static final int CODE_COUNT = 4;
    // 干扰线数量
    private static final int LINE_COUNT = 20;
    // 验证码在Redis中的过期时间（单位：秒）
    private static final long CAPTCHA_EXPIRE_TIME = 300;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成验证码图片并写入响应流
     *
     * @param captchaKey 验证码的Redis Key
     * @param response   HttpServletResponse
     * @throws IOException 如果写入响应流失败
     */
    public void generateCaptcha(String captchaKey, HttpServletResponse response) throws IOException {
        // 创建验证码对象
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(WIDTH, HEIGHT, CODE_COUNT, LINE_COUNT);

        // 将验证码存储到Redis中，并设置过期时间
        stringRedisTemplate.opsForValue().set(captchaKey, lineCaptcha.getCode(), CAPTCHA_EXPIRE_TIME, TimeUnit.SECONDS);

        // 设置响应内容类型为图片
        response.setContentType("image/png");

        // 将验证码图片写入响应流
        lineCaptcha.write(response.getOutputStream());
    }

    /**
     * 验证用户输入的验证码是否正确
     *
     * @param captchaKey  验证码的Redis Key
     * @param userCaptcha 用户输入的验证码
     * @return 验证码是否正确
     */
    public boolean validateCaptcha(String captchaKey, String userCaptcha) {
        // 从Redis中获取生成的验证码
        String redisCaptcha = stringRedisTemplate.opsForValue().get("captcha:"+captchaKey);

        // 比较用户输入的验证码和Redis中的验证码
        if (redisCaptcha == null || userCaptcha == null) {
            return false;
        }
        return redisCaptcha.equalsIgnoreCase(userCaptcha);
    }

    /**
     * 清除Redis中的验证码
     *
     * @param captchaKey 验证码的Redis Key
     */
    public void clearCaptcha(String captchaKey) {
        stringRedisTemplate.delete("captcha:"+captchaKey);
    }
}